﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Telerik.Web.Mvc;
using ProjectManagement.Models;
using Projectmanagement.Utl;
using Projectmanagement.Entity;

namespace Projectmanagement.Controllers
{
    public class TracelController : Controller
    {
        //
        // GET: /Tracel/

        public ActionResult Index(bool? autoUpload, bool? multiple)
        {
            ViewData["autoUpload"] = autoUpload ?? true;
            ViewData["multiple"] = multiple ?? true;
            return View();
        }
        public ActionResult SaveTravelFile(IEnumerable<HttpPostedFileBase> attachments)
        {            // The Name of the Upload component is "attachments"    
            if (attachments != null)
            {
                foreach (var file in attachments)
                {                // Some browsers send file names with full path. This needs to be stripped.                
                    var fileName = Path.GetFileName(file.FileName);
                    var physicalPath = Path.Combine(Server.MapPath("~/Upload"), fileName);
                    // The files are not actually saved in this demo                
                    file.SaveAs(physicalPath);
                }
            }
            // Return an empty string to signify success           
            return Content("");
        }
        public ActionResult RemoveTravelFile(string[] fileNames)
        {
            // The parameter of the Remove action must be called "fileNames"            
            foreach (var fullName in fileNames)
            {
                var fileName = Path.GetFileName(fullName);
                var physicalPath = Path.Combine(Server.MapPath("~/Upload"), fileName);
                // TODO: Verify user permissions                
                if (System.IO.File.Exists(physicalPath))
                {
                    // The files are not actually removed in this demo                    
                    System.IO.File.Delete(physicalPath);
                }
            }
            // Return an empty string to signify success           
            return Content("");
        }
        [GridAction]
        public ActionResult _SelectIndex(int? conferenceid)
        {
            return View(new GridModel(DQ.GetTracel()));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _SaveAjaxEditing(int id, int? conferenceid)
        {
            var item = CH.GetDataByID<Tracel>(id);
            if (TryUpdateModel(item))
            {
                CH.Edit<Tracel>(item);
            }
            if (!string.IsNullOrWhiteSpace(item.TravelFileId))
            {
                string[] list = item.TravelFileId.Split(',');
                UploadFiles(item.ID, list);
            }
            return View(new GridModel(DQ.GetTracel()));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _InsertAjaxEditing(int? conferenceid)
        {

            var item = new Tracel();

            if (TryUpdateModel(item))
            {
                CH.Create<Tracel>(item);
            }
            if (!string.IsNullOrWhiteSpace(item.TravelFileId))
            {
                string[] list = item.TravelFileId.Split(',');
                UploadFiles(item.ID, list);
            }
            return View(new GridModel(DQ.GetTracel()));
        }

        public void UploadFiles(int id, string[] filesName)
        {
            for (int i = 0; i < filesName.Length; i++)
            {
                if (!string.IsNullOrEmpty(filesName[i]))
                {
                    var physicalPath = Path.Combine("/Upload", filesName[i]);
                    UploadFile tf = new UploadFile();
                    tf.FileID = id;
                    tf.FileName = filesName[i];
                    tf.FileUrl = physicalPath;
                    tf.FileType = "旅行社";
                    CH.Create(tf);
                }
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _DeleteAjaxEditing(int id, int? conferenceid)
        {
            CH.Delete<Tracel>(id);
            return View(new GridModel(DQ.GetTracel()));
        }

        public ActionResult SaveConstructFile(IEnumerable<HttpPostedFileBase> ConstructFileId)
        {            // The Name of the Upload component is "attachments"             
            foreach (var file in ConstructFileId)
            {                // Some browsers send file names with full path. This needs to be stripped.                
                var fileName = Path.GetFileName(file.FileName);
                var physicalPath = Path.Combine(Server.MapPath("~/Upload"), fileName);
                // The files are not actually saved in this demo                
                file.SaveAs(physicalPath);
            }
            // Return an empty string to signify success           
            return Content("");
        }
        public ActionResult RemoveConstructFile(string[] fileNames)
        {
            // The parameter of the Remove action must be called "fileNames"            
            foreach (var fullName in fileNames)
            {
                var fileName = Path.GetFileName(fullName);
                var physicalPath = Path.Combine(Server.MapPath("~/Upload"), fileName);
                // TODO: Verify user permissions                
                if (System.IO.File.Exists(physicalPath))
                {
                    // The files are not actually removed in this demo                    
                    System.IO.File.Delete(physicalPath);
                }
            }
            // Return an empty string to signify success           
            return Content("");
        }

        [HttpPost]
        public ActionResult GetFile(int id)
        {
            //var ss = CH.DB.TaskFiles.Where(x => x.TaskId == id).ToList();
            //var selectList = ss.ToList().Select(a => new SelectListItem
            //{
            //    Text = a.ID.ToString(),
            //    Value = a.FileName.ToString()
            //});
            //return Json(selectList, JsonRequestBehavior.AllowGet);
            var ss = CH.DB.UploadFiles.Where(x => x.FileID == id && x.FileType == "旅行社").ToList();
            return Json(ss, JsonRequestBehavior.AllowGet);

        }

        [HttpPost]
        public JsonResult DeleteFile(int id)
        {
            try
            {
                UploadFile tf = CH.DB.UploadFiles.Find(id);
                var fileName = Path.GetFileName(tf.FileName);
                var physicalPath = Path.Combine(Server.MapPath("~/Upload"), fileName);
                // TODO: Verify user permissions                
                if (System.IO.File.Exists(physicalPath))
                {
                    // The files are not actually removed in this demo                    
                    System.IO.File.Delete(physicalPath);
                }
                CH.Delete<UploadFile>(id);
                return Json("OK");
            }
            catch (Exception)
            {
                return Json("");
            }
        }

    }
}
